package cn.itcast.usermanager.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.druid.util.StringUtils;

import cn.itcast.usermanager.pojo.User;
import cn.itcast.usermanager.service.UserService;

@Controller()
@RequestMapping("rest/user")
public class NewUserController {
	@Autowired
	private UserService userService;
	@GetMapping("{id}")
	public ResponseEntity<User> queryUserById(@PathVariable("id") Long id){
		try {
			//参数列表错误,响应400
			if (id.longValue()<1) {
				return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
			}
			User user = userService.queryUserById(id);
			//int a = 6/0;
			//请求资源不存在,响应404
			if (user==null) {
				return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
			}
			return ResponseEntity.status(HttpStatus.OK).body(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
	}
	@PostMapping
	public ResponseEntity<Void> saveUser(User user){
		try {
			if (user==null||StringUtils.isEmpty(user.getUserName())) {
					return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
			}
			boolean b = userService.save(user);
			if (b) {
				return ResponseEntity.status(HttpStatus.CREATED).build();
			}
		} catch (Exception e) {
			e.printStackTrace();
			
		}
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
	}
	@PutMapping
	public ResponseEntity<Void> updateUser(User user){
		try {
			if (user==null||user.getId()==null) {
				return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
			}
			Boolean b = userService.update(user);
			if (b) {
				//204
				return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
	}
	@DeleteMapping
	public ResponseEntity<Void> deleteUser(@RequestParam("ids")List<Object> ids){
		try {
			if (ids==null||ids.size()==0) {
				return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
			}
			Boolean b = userService.delete(ids);
			if (b) {
				return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
	}
}
